<template>
  <div class="calendar-box">
    <div class="calendar-header">
      <div class="calendar-header-left" @click="handleTask">
        <span>日程</span>
        <i class="fal fa-calendar-alt"></i>
      </div>
      <div class="calendar-header-right" @click="handleCreate">创建</div>
    </div>
    <div class="calendar-body">
      <!-- 年份 月份 -->
      <section class="calendar-month">
        <span @click="prevMonth">
          <i class="fal fa-angle-left"></i>
        </span>
        <span class="cur-year-month">{{ curMonth }}</span>
        <span @click="nextMonth">
          <i class="fal fa-angle-right"></i>
        </span>
        <span class="cur-today" @click="handleToday">今天</span>
      </section>
      <!-- 日期 -->
      <div class="calendar-days" :class="{ 'collapse-days': collapseDays }">
        <!-- 星期 -->
        <ul class="week-header">
          <li v-for="(text, i) of weekHeader" :key="i" class="day">
            {{ text }}
          </li>
        </ul>
        <ul v-for="(week, i) of days" :key="i" class="week" :class="{ select: isSelectWeek(week) }">
          <li
            v-for="(day, j) of week"
            :key="j"
            :class="{
              'other-month': day.prevMonth || day.nextMonth,
              today: day.isToday,
              select: isSelect(day),
              task: isTask(day),
            }"
            class="day"
            @click="selectDay(day)"
          >
            <span>{{ day.sDay }}</span>
          </li>
        </ul>
      </div>
      <!-- 展开 -->
      <div v-show="collapseDays" class="collapse-btn" @click="handleCollapse">
        <span>展开全月</span>
        <i class="fal fa-angle-down"></i>
      </div>
      <!-- 收起 -->
      <div v-show="!collapseDays" class="collapse-btn" @click="handleCollapse">
        <span>收起</span>
        <i class="fal fa-angle-up"></i>
      </div>
      <!-- 选中的日程 -->
      <section v-show="showList" class="calendar-tasks" style="max-height: 160px; overflow: auto">
        <section v-for="item in currentTasks" :key="item" :title="item.CALENDAR_TITLE" class="task">
          <span :style="{ background: item.CALENDAR_COLOR }" class="type">日程</span>
          <span class="text" @click="editTask(item)"> {{ item.CALENDAR_TITLE }}</span>
        </section>
      </section>
    </div>
  </div>
  <div v-show="calendarEdit">
    <calendar-handle :select-date="selectCalendar" />
  </div>
  <div v-show="calendarTask">
    <calendar-task />
  </div>
</template>

<script>
  import {
    defineComponent,
    reactive,
    toRefs,
    onMounted,
    onBeforeUnmount,
    computed,
    nextTick,
  } from 'vue';
  import dayjs from 'dayjs';
  import Util from '@/helper/util';
  import VueEvent from '@/helper/event';
  import { dateFormat, getCurrentUser } from '@jecloud/utils';
  import CalendarHandle from '@/views/board-home/components/calendar-handle.vue';
  import CalendarTask from '@/views/board-home/components/calendar-task.vue';
  import { GetCalendarSchedule } from '@/api';
  import {
    HOME_CALENDAR_CREATE_VISIBLE,
    HOME_CALENDAR_EDIT_VISIBLE,
    HOME_CALENDAR_TASK_VISIBLE,
    HOME_CALENDAR_CLOSE_MODAL,
    HOME_CALENDAR_LIST_EDIT,
    HOME_CALENDAR_UPDATE_SUCCESS,
  } from '@/helper/constant';
  export default defineComponent({
    name: 'CalendarBox',
    components: {
      CalendarHandle,
      CalendarTask,
    },
    setup() {
      const state = reactive({
        currentDate: new Date(), // 当前日期
        selectDate: new Date(), // 选中日期
        tasks: {}, // 日程数据
        weekHeader: ['一', '二', '三', '四', '五', '六', '日'],
        collapseDays: true, // 默认折叠
        currentTasks: [], // 选中日期日程
        calendarEdit: false, //编辑日程弹窗
        calendarTask: false, //月日程弹窗
        selectCalendar: dateFormat(new Date(), 'YYYY-MM-DD'), //创建日程用的时间
      });
      const methods = {
        initTasks(weeks) {
          //获得当前月的日程
          const userId = getCurrentUser()?.id;
          const deptId = getCurrentUser()?.organization.id; //部门id
          const startDate = weeks[0][0].sDate + ' 00:00:00';
          const endDate = weeks[weeks.length - 1][6].sDate + ' 23:59:59';
          const params = {
            tableCode: 'JE_SYS_CALENDAR',
            limit: -1,
            startTime: startDate,
            endTime: endDate,
          };
          GetCalendarSchedule(params).then((res) => {
            if (res.code == 1000 && res.success) {
              let tasks = res.data.rows;
              const taskObj = {};
              for (let task of tasks) {
                const startDate1 = dayjs(task.CALENDAR_STARTTIME).toDate();
                const endDate1 = dayjs(task.CALENDAR_ENDTIME).toDate();
                // 计算任务周期
                const days = dayjs(dateFormat(endDate1, 'YYYY-MM-DD')).diff(
                  dateFormat(startDate1, 'YYYY-MM-DD'),
                  'day',
                );
                // 为每一天增加任务新
                for (let i = 0; i <= days; i++) {
                  const dateStr = dateFormat(startDate1, 'YYYY-MM-DD');
                  taskObj[dateStr] = taskObj[dateStr] || [];
                  taskObj[dateStr].push(task);
                  startDate1.setDate(startDate1.getDate() + 1);
                }
              }
              state.tasks = taskObj;
              if (state.selectDate) {
                state.currentTasks = state.tasks[dateFormat(state.selectDate, 'YYYY-MM-DD')];
              }
            }
          });
        },
        getDays() {
          const year = state.currentDate.getFullYear();
          const month = state.currentDate.getMonth();
          const weeks = Util.calendarWeeks(year, month);
          methods.initTasks(weeks);
          return weeks;
        },
        isSelectWeek(week) {
          //选中标记周
          // const dayStr = Ext.Date.format(this.selectDate, 'Y-m-d');
          const dayStr = dateFormat(state.currentDate, 'YYYY-MM-DD');
          let select = false;
          for (let i = 0; i < week.length; i++) {
            if (week[i].sDate == dayStr) {
              select = true;
              break;
            }
          }
          return select;
        },
        isTask(day) {
          //任务标记
          return state.tasks[day.sDate] !== undefined;
        },
        handleCollapse() {
          //日期展开/收缩
          state.collapseDays = !state.collapseDays;
        },
        selectDay(day) {
          //选中日期
          state.selectDate = day.sDate;
          state.selectCalendar = day.sDate;
          state.currentTasks = state.tasks[day.sDate] || [];
          if (day.prevMonth) {
            methods.prevMonth();
          } else if (day.nextMonth) {
            methods.nextMonth();
          }
        },
        prevMonth() {
          //上一个月
          let prevMonthDate = dayjs(dateFormat(state.currentDate)).subtract(1, 'month');
          state.currentDate = prevMonthDate.toDate();
          state.collapseDays = false;
        },
        nextMonth() {
          //下一个月
          let nextMonthDate = dayjs(dateFormat(state.currentDate)).add(1, 'month');
          state.currentDate = nextMonthDate.toDate();
          state.collapseDays = false;
        },
        handleToday() {
          //今天
          state.currentDate = state.selectDate = new Date();
          state.collapseDays = false;
          nextTick(() => {
            // 选中日期
            const day = { sDate: dateFormat(state.selectDate, 'YYYY-MM-DD') };
            methods.selectDay(day);
          });
        },
        isSelect(day) {
          //选中标记
          return day.sDate == dateFormat(state.selectDate, 'YYYY-MM-DD');
        },
        handleTask() {
          //查看日程列表
          state.calendarTask = true;
          VueEvent.emit(HOME_CALENDAR_TASK_VISIBLE);
        },
        handleCreate() {
          //创建日程
          state.calendarEdit = true;
          VueEvent.emit(HOME_CALENDAR_CREATE_VISIBLE);
        },
        editTask(task) {
          //编辑当前日程
          state.calendarEdit = true;
          VueEvent.emit(HOME_CALENDAR_EDIT_VISIBLE, task);
        },
        closeCalendarEdit() {
          //关闭编辑任务弹窗
          state.calendarEdit = false;
          // methods.initTasks(days);
          methods.getDays();
        },
        openCalendarEdit() {
          //打开编辑任务弹窗
          state.calendarEdit = true;
        },
      };
      let days = computed(() => {
        return methods.getDays();
      });
      let curMonth = computed(() => {
        // const year = state.currentDate.getFullYear();
        // const monthStr = parseInt(state.currentDate.getMonth() + 1);
        // const month = monthStr < 10 ? `0${monthStr}` : `${monthStr}`;
        // return `${year}年${month}月`;
        return dateFormat(state.currentDate, 'YYYY年MM月');
      });
      let showList = computed(() => {
        const currentDate = dateFormat(state.currentDate, 'YYYY-MM-DD');
        const selectDate = dateFormat(state.selectDate, 'YYYY-MM-DD');
        if (
          currentDate.split('-')[0] === selectDate.split('-')[0] &&
          currentDate.split('-')[1] === selectDate.split('-')[1]
        ) {
          return true;
        }
        return false;
      });
      onMounted(() => {
        VueEvent.on(HOME_CALENDAR_CLOSE_MODAL, methods.closeCalendarEdit);
        VueEvent.on(HOME_CALENDAR_LIST_EDIT, methods.openCalendarEdit);
      });
      onBeforeUnmount(() => {
        VueEvent.off(HOME_CALENDAR_CLOSE_MODAL);
        VueEvent.off(HOME_CALENDAR_LIST_EDIT);
      });
      return {
        days,
        curMonth,
        showList,
        ...toRefs(state),
        ...methods,
      };
    },
  });
</script>
<style>
  .calendar-box .je-modal--wrapper.type--modal .je-modal--body ::-webkit-scrollbar {
    width: 0;
    height: 0;
  }
  .calendar-box .je-modal--wrapper.type--dialog .je-modal--body::-webkit-scrollbar {
    width: 0;
    height: 0;
  }
</style>
<style scoped lang="less">
  .calendar-box {
    width: 100%;
    border-radius: 4px;
    background-color: #ffffff;
    padding: 0 20px;
    .calendar-header {
      width: 100%;
      height: 60px;
      line-height: 60px;
      display: inline-flex;
      align-items: center;
      justify-content: space-between;
      border-bottom: 1px solid #ecedf0;
      .calendar-header-left {
        display: inline-flex;
        align-items: center;
        cursor: pointer;
        span {
          font-size: 18px;
          color: #3f3f3f;
          font-weight: bold;
          padding-right: 4px;
        }
        i {
          font-size: 14px;
          color: #8d98ab;
        }
      }
      .calendar-header-right {
        font-size: 14px;
        color: #8d98ab;
        cursor: pointer;
      }
    }

    .calendar-body {
      width: 100%;
      padding: 20px 0;
      .calendar-month {
        text-align: center;
        position: relative;
        span {
          color: #2f6bcf;
          display: inline-block;
          padding: 4px 8px;
          cursor: pointer;
          font-size: 14px;
        }
        .cur-year-month {
          width: 100px;
          text-align: center;
          cursor: auto;
        }
        .cur-today {
          position: absolute;
          right: 0;
        }
      }
      .calendar-days {
        .week,
        .week-header {
          padding: 0;
          margin: 4px 0;
          .day {
            width: 14%;
            color: #333333;
            text-align: center;
            line-height: 38px;
            list-style-type: none;
            display: inline-block;
            font-size: 12px;
          }
        }
        .week {
          .day {
            cursor: pointer;
            position: relative;
          }
          .other-month {
            color: #d0d0d0;
          }
          .today span,
          .select span {
            background: #f2f2f2;
            border-radius: 12px;
            padding: 2px 8px;
          }
          .select span {
            color: #ffffff;
            background: #2f6bcf;
          }
          .task:after {
            position: absolute;
            content: ' ';
            padding: 2px;
            border-radius: 100%;
            bottom: 3px;
            left: 50%;
            margin-left: -1px;
            background: #2f6bcf;
          }
        }
      }
      .collapse-days {
        .week {
          display: none;
        }
        .week.select {
          display: initial;
        }
      }

      .collapse-btn {
        margin: 10px 0;
        height: 25px;
        line-height: 25px;
        text-align: center;
        color: #d0d0d0;
        cursor: pointer;
        position: relative;
        span {
          padding-right: 4px;
        }
      }
    }

    .calendar-tasks {
      width: 100%;
      max-height: 160px;
      overflow: auto;
      .task {
        height: 32px;
        line-height: 32px;
        font-size: 12px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        .type {
          margin: 0 4px;
          border-radius: 12px;
          background: #2f6bcf;
          color: #ffffff;
          padding: 2px 8px;
        }
        .text {
          color: #333333;
          cursor: pointer;
        }
        .text:hover {
          color: #2f6bcf;
        }
      }
    }
    .calendar-tasks::-webkit-scrollbar {
      width: 0;
      height: 0;
    }
  }
</style>
